﻿<?php 
/**
 * @package ogame-functions
 * @author Padre386
 * @version 1.0
 */
/*
Plugin Name: ogame-functions
Description: Functions for work with OGame GalaxyTool
Author: Padre386
Version: 1.0
Author URI: http://padre386.ru
*/

function ogame_alliance_progress( $atts, $content = null) {
	global $post,$wpdb, $current_user;
	
$cnt="<script type='text/javascript' src='https://www.google.com/jsapi'></script>
    <script type='text/javascript'>
        google.load('visualization', '1', {packages:['corechart']});
        google.load('visualization', '1', {packages:['corechart']});
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            var data = new google.visualization.DataTable();

            data.addColumn('string', 'Year');";
	

	 
    extract(shortcode_atts(array(
        'alliance' => '',
		'score_from' => '1000000',
		'score_to' => '50000000',
    ), $atts));
     

	if($alliance==''){		
		$gtOGamePlayerId='';
		$gtOGamePlayerAllianceName='';

		$gtDataPlayerId = $wpdb->get_results("SELECT ogame_playerid, allyname FROM gt_players
		LEFT JOIN gt_alliances ON gt_alliances.id=gt_players.alliance_id
		WHERE gt_players.playername='" . xprofile_get_field_data(2, $current_user->id) . "'");
		if ($gtDataPlayerId) {
			foreach ($gtDataPlayerId as $uRow) {
				$gtOGamePlayerId=$uRow->ogame_playerid;
				$gtOGamePlayerAllianceName=$uRow->allyname;
			}
		}
		if($gtOGamePlayerId==''||$gtOGamePlayerAllianceName==''){
			echo "График развития членов альянса не может быть вам показан, т.к. вы не состоите ни в одном альянсе, либо не авторизованы на сайте. 
			<br>Если это не так - пожалуйста, свяжитесь с администратором сайта для решения возникшей проблемы.";
			
			return '';
		}else{
			$alliance=$gtOGamePlayerAllianceName;
		}
	}




	$allyName = $alliance;
	$scoreFrom = $score_from;
	$scoreTo = $score_to;
	$ts = array();
    $data = array();
	 
	 
	$players = $wpdb->get_results("SELECT gt_players.id, gt_players.playername, gt_players.points FROM gt_players JOIN gt_alliances ON gt_alliances.id=gt_players.alliance_id WHERE allyname='".$allyName."' ORDER BY playername");
	   
    if ($players) {
        foreach ($players as $pRow) {
            $cnt=$cnt."data.addColumn('number', '".$pRow->playername. "');\n";

			
			$sql="SELECT points as rank, CONCAT(`year`, '-',`month`, '-',`day`) AS D,
                  UNIX_TIMESTAMP(CONCAT(`year`, '-',`month`, '-',`day`)) AS TS
                  FROM gt_players_history
                  WHERE gt_players_history.player_id=" .$pRow->id. "
                  AND UNIX_TIMESTAMP(CONCAT(`year`, '-',`month`, '-',`day`))>=UNIX_TIMESTAMP(NOW())-(86400*15)
                  ORDER BY TS ASC";
			
			$dataForPlayer = $wpdb->get_results($sql);
				if ($dataForPlayer) {
					$personData = array();
					foreach ($dataForPlayer as $dfpRow) {
						$ts[$dfpRow->D] = $dfpRow->TS;
						$personData[$dfpRow->D] = $dfpRow->rank;
					}
					$data[$pRow->playername] = $personData;
					
				}else{
                    echo "Нет данных для: ".$pRow->playername.", свяжитесь с администратором сайта<br>";
                }
			}
    }
	 


        $ts = array_unique($ts);
        asort($ts);
		
		$cnt=$cnt."data.addRows([";


        foreach ($ts as $dateText => $t) {
            $cnt=$cnt."['$dateText', ";
            foreach ($data as $playerName => $personData) {
                $rank = $personData[$dateText];
                if ($rank == '') {
                    $rank = 0;
                }
                $cnt=$cnt.$rank . ", ";
            }
            $cnt=$cnt."],\n";
        }

	$cnt=$cnt."]);
            var options = {
                legend:{
                    textStyle:{color:'blue', fontSize:14}
                },
                vAxis:{
                    title:'Очки',
                    logScale:true,
                    viewWindow:{max:".$scoreTo.", min:".$scoreFrom."},
                    gridlines:{
                        count:25
                    }
                },
                xAxis:{
                    title:'Дата'
                },
                chartArea:{
                    height:'95%'
                },
                width:1000,
                height:4000,
            };
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>
    <div id='chart_div'></div>";

	echo $cnt;
}
add_shortcode('ogame-alliance-progress', 'ogame_alliance_progress');


function ogame_cookie_expiration( $expiration, $user_id, $remember ) {
    return $remember ? $expiration : 60*60*48;
}
add_filter( 'auth_cookie_expiration', 'ogame_cookie_expiration', 99, 3 );